<template>
    <Dialog v-model:visible="visible" header="实例数据" :style="{ width: '80rem' }">
        <div class="grid">
            <div class="flex align-items-center  col-3">
                <label class="mr-2 w-5rem">全局搜索</label>
                <InputText v-model="queryFormState._full" class="flex-auto"/>
            </div>
            <div v-if="expandedSearch" v-for="col in field.filter(item => !item.meta.hidden)"
                 class="flex align-items-center col-3">
                <label class="mr-2 w-5rem text-right">{{ col.name }}</label>
                <InputText v-model="queryFormState[col.field_id]" class="flex-auto w-5rem"/>
                <div class="ml-2">
                    <Checkbox v-model="queryFormState[col.field_id + '_like']" :value="true"/>
                    <label> 精确 </label>
                </div>
            </div>
            <div class=" col-3">
                <Button class='ml-2' @click="querySubmit"
                        label="查询"></Button>
                <Button
                    @click="resetQuery"
                    class='ml-2'
                    severity="secondary"
                    label="重置"></Button>
                <Button class='ml-2' :label="expandedSearch === true ? '收起' : '展开搜索'"
                        :icon="'pi ' + (expandedSearch === true ? 'pi-chevron-up' : 'pi-chevron-down')"
                        severity="secondary" text
                        @click="expandedSearch = !expandedSearch"/>
            </div>
        </div>
        <div class="flex justify-content-end">
            <Button icon="pi pi-sliders-v" severity="secondary" outlined
                    @click="columnsToggle"/>

        </div>
        <div class="h-1rem"></div>
        <DataTable :value="instanceList" :rows="10" dataKey="id" :loading="instanceLoading" scrollable
                   scrollHeight="55vh">
            <Column v-for="col in field.filter(item => !item.meta.hidden)" :key="col.id" :field="col.field_id"
                    :header="col.name"></Column>
        </DataTable>

        <Paginator
            :page="queryState.page"
            :rows="queryState.rows"
            :totalRecords="total"
            :rowsPerPageOptions="[10, 20, 30, 50, 100]"
            template="FirstPageLink PrevPageLink PageLinks  NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
            currentPageReportTemplate="{totalRecords}条"
            @page="(PageState) => {queryState.page = PageState.page;queryState.rows = PageState.rows;instanceRun(schema_id, queryState)}">
        </Paginator>
    </Dialog>

    <Menu ref="columnsMenu" :model="field" :popup="true">
        <template #item="{ item, props }">
            <a v-ripple class="flex items-center" v-bind="props.action" @click="(e) => e.stopPropagation()">
                <span v-if="item.meta.hidden" class="pi pi-eye-slash" @click="(e) => field_update(item, false)"/>
                <span v-else class="pi pi-eye" @click="(e) => field_update(item, true)"/>
                <span>{{ item.name }}</span>
            </a>
        </template>
    </Menu>
    <ConfirmDialog></ConfirmDialog>
</template>
<script setup>
import IconField from 'primevue/iconfield';
import InputIcon from 'primevue/inputicon';
import ConfirmDialog from 'primevue/confirmdialog';
import {cloneDeep} from 'lodash-es';
import {reactive, ref, computed, watch} from "vue";
import {useRequest} from 'vue-request';
import {
    ApiInstanceList,
    ApiInstanceCreate, ApiInstanceImportExcel,
    ApiFieldUpdate, ApiInstancelDetail, ApiInstanceUpdate
} from "@/api/cmdb.js";
import * as yup from "yup";
import {Form, Field} from "vee-validate";
import {useToast} from "primevue/usetoast";
import {useRoute} from "vue-router";
import router from "@/router.js";
import {useConfirm} from "primevue/useconfirm";
import Select from 'primevue/select';

const confirm = useConfirm();
const toast = useToast();
const route = useRoute();
const schema_id = ref()


defineExpose({
    visible: (index, data, origin) => {
        visible.value = true;
        instanceList.value = data.list
        field.value = data.field
        total.value = data.total

        queryState.query = origin.query
        schema_id.value = origin.schema_id
        keep_query.value = JSON.parse(JSON.stringify(origin.query))

        // 初始化默认查询条件
        initQuery()
    },
})

const keep_query = ref([])
const query = ref()
const parentInstanceData = ref()
const expandedSearch = ref(false)
const columnsMenu = ref();
const visible = ref(false)

const instanceImportFormState = reactive({})

const queryForm = reactive({})
const queryFormState = reactive({})
const queryState = reactive({
    schema_id: schema_id,
    page: 0,
    rows: 10,
    query: []
})

const instanceList = ref([])
const field = ref([])
const total = ref(0)

const {
    data: instanceData,
    loading: instanceLoading,
    run: instanceRun,
//    refresh: instanceRefresh
} = useRequest(ApiInstanceList, {
    manual: true,
    defaultParams: [schema_id, {
        page: queryState.page,
        rows: queryState.rows
    }],
    onSuccess: (e) => {
        instanceList.value = e.data.list
        field.value = e.data.field
        total.value = e.data.total
    }
})


function initQuery() {
    keep_query.value.forEach(item => {
        queryFormState[item['field']] = item['value']
        if (item['comparison'] === 'like') {
            queryFormState[item['field'] + '_like'] = []
        } else {
            queryFormState[item['field'] + '_like'] = [true]
        }
    })

    queryState.query = keep_query.value
}

const querySave = async () => {
    visible.querySave = true
}

const instanceSchema = ref(null);

const generateSchema = (field) => {
    // 动态字段表单校验
    const schemaField = {};
    field.forEach(field => {
        //   if (field.name === 'email') {
        schemaField[field.field_id] = yup.string();
        //   } else if (field.name === 'age') {
        //     schemaFields[field.name] = yup.number().min(18, '年龄必须大于等于18').required('年龄为必填项');
        //   }
    });

    return schemaField
}


const instanceSubmit = async (values) => {
    let query = []
    let result;
    if (values.instance_id) {
        result = await ApiInstanceUpdate({instance_id: values.instance_id, data: values})
    } else {
        result = await ApiInstanceCreate({schema_id: schema_id, data: values})
    }
    if (result.code === 0) {
        toast.add({severity: 'success', summary: '成功', detail: result.msg, life: 3000});
        visible.instanceCreate = false
        instanceRefresh()
    } else {
        toast.add({severity: 'error', summary: '错误', detail: result.msg, life: 3000});
    }
}


const filterOption = (input, option) => {
    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

function clearQueryForm() {
    Object.keys(queryForm).forEach(key => {
        queryForm[key] = '';
    });
}

const queryParams = computed(() => {
    let params = []
    const searchDict = {...queryForm}
    Object.keys(searchDict).forEach(item => {
        params.push({
            id: item,
            value: searchDict[item],
        })
    })
    return params
})
let lastIndex = -1

const swiftRemoveSubmit = async (name) => {
    const result = await ApiModelSwiftRemove({model: 'host', swift_name: name})
    if (result.code === 0) {
        message.success(result.msg)
        modelRun()
    } else {
        message.error(result.msg)
    }
}


const upload = async () => {
    instanceImportLoading.value = true
    const formData = new FormData();
    formData.append('schema_id', schema_id);
    formData.append('unique', instanceImportFormState.unique);
    formData.append('file', fileupload.value.files[0]);
    const result = await ApiInstanceImportExcel(formData)
    if (result.code === 0) {
        toast.add({severity: 'success', summary: '成功', detail: result.msg, life: 3000});
        visible.instanceImport = false
    } else {
        toast.add({severity: 'error', summary: '错误', detail: result.msg, life: 3000});
    }
    instanceImportLoading.value = false

};

const columnsToggle = (event) => {
    columnsMenu.value.show(event);
};

const field_update = async (data, hidden) => {
    data.meta.hidden = hidden

    const result = await ApiFieldUpdate({id: data.id, meta: data.meta})
    if (result.code === 0) {
        await instanceRun({...queryState})
    } else {
        toast.add({severity: 'error', summary: '错误', detail: result.msg, life: 3000});
    }
}

const openEditor = async (data) => {
    const result = await ApiInstancelDetail(data.instance_id)
    if (result.code === 0) {
        initialValues.value = result.data.detail
        visible.instanceCreate = true
    } else {
        toast.add({severity: 'error', summary: '错误', detail: result.msg, life: 3000});
    }

}

const querySubmit = async () => {
    // 拼接查询参数提交给后端
    queryState.query = []
    Object.entries(queryFormState).forEach(([key, value]) => {
        if (!key.endsWith('_like')) {
            let comparison = 'like'
            const like_key = key + '_like'
            if (like_key in queryFormState && queryFormState[like_key][0] === true) {
                comparison = '='
            }
            queryState.query.push({
                field: key,
                value: value,
                comparison: comparison
            })
        }
    });
    await instanceRun({...queryState})
}

const resetQuery = () => {
    queryState.query = [];
    Object.keys(queryFormState).forEach(key => {
        delete queryFormState[key];
    });
    initQuery()
    instanceRun(queryState)
}

</script>